"use strict";

import $P from './public.js';
import $glob from '../../../globalConfig';
const prefix = $glob.MAJOR + "_" + $glob.MINOR + "_";
import $encryption from './encryption';

/**
 * 设置本地存储
 * @param key
 * @param val
 * @param type 1: localStorage  2/其他: localSession
 * @constructor
 * by J.sky
 */
function Set(key, val,type=1){
  let d = {
    "data": val,
    "time": new Date().getTime(),
  };
  d = JSON.stringify(d);
  if(type === 1){
    window.localStorage.setItem( prefix + key, $glob.HTTP_CRYPTO ? $encryption.Encode(d) : d );
  }else {
    window.sessionStorage.setItem( prefix + key, $glob.HTTP_CRYPTO ? $encryption.Encode(d) : d );
  }
}

/**
 * 获取本地存储
 * @param key
 * @param type 1: localStorage  2/其他: localSession
 * @returns {null}
 * @constructor
 * by J.sky
 */
function Get(key,type = 1){
  if(!$P.Invalid(key))
  {
    let v;
    if(type === 1){
      v = window.localStorage.getItem(prefix + key);
    }else {
      v = window.sessionStorage.getItem(prefix + key);
    }

    if($P.Invalid(v)) return null;
    let j,
      d = $glob.HTTP_CRYPTO ? $encryption.Decode(v) : v;
    try {
      j = JSON.parse(d);
      return j.data;
    }catch(e) {
      return null;
    }
  }
  return null;
}

/**
 * 删除指定本地存储
 * @param key
 * @param type 1: localStorage  2/其他: localSession
 * @constructor
 * by J.sky
 */
function Del(key,type=1) {
  if(type === 1){
    return window.localStorage.removeItem(prefix + key);
  }else {
    return window.sessionStorage.removeItem(prefix + key);
  }
}

/**
 * 清空本地存储
 * @param type 1: localStorage  2: localSession  其他则：local 和 session 全清除
 * @constructor
 * by J.sky
 */
function Clear(type = 1) {
  if(type === 1){
    return window.localStorage.clear();
  }else if(type === 2){
    return window.sessionStorage.clear();
  }else{
    window.localStorage.clear();
    window.sessionStorage.clear();
    return true;
  }

}
export default {
  Set,
  Get,
  Del,
  Clear,
};
